import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

//引入dio实现http请求
import 'config/httpHeaders.dart';
//引入伪造的请求头

class DioHttp extends StatefulWidget {
  @override
  _DioHttpState createState() => _DioHttpState();
}

class _DioHttpState extends State<DioHttp> {
  TextEditingController _typeController = TextEditingController();

  String showText = '欢迎来到这里';

  String showText2 = '用于显示伪造请求头请求的数据';

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Scaffold(
        appBar: AppBar(
          title: Text('Dio实现Http请求'),
        ),
        body: ListView(
          children: <Widget>[
            Column(
              children: <Widget>[
                TextField(
                  controller: _typeController,
                  decoration: InputDecoration(
                    contentPadding: const EdgeInsets.all(10.0),
                    labelText: '输入类型',
                    helperText: '请输入你喜欢的类型',
                  ),
                  autofocus: false, //不会自动获取焦点
                ),
                RaisedButton(
                  child: Text('完成选择'),
                  onPressed: () {
                    _chioceAction();
                  },
                ),
                Text(
                  showText,
                  overflow: TextOverflow.ellipsis, //处理好overflow的问题
                  maxLines: 1,
                ),
                RaisedButton(
                  child: Text('伪造请求头请求极客时间网站'),
                  onPressed: () {
                    _jikeAction();
                  },
                ),
                Text(
                  showText2,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  //get/post请求的实现
  void _chioceAction() {
    print('开始选择你喜欢的类型....');
    if (_typeController.text.toString() == '') {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
              title: Text('不能放弃选择(输入不能为空)'),
            ),
      );
    } else {
      setState(() {
        getHttp(_typeController.text.toString()).then((val) {
          showText = val['data']['name'].toString();
        });
      });
    }
  }

  Future getHttp(String typeText) async {
    //async和await两个也是实现异步操作
    //使用Future的返回值可以使用then接收类似一种异步的完成
    try {
      Response response;
      var data = {'name': typeText};
      /*post方法*/
      response = await Dio().post(
        'https://www.easy-mock.com/mock/5c724cf7cb92cf5c294de75a/example/postTest',
        queryParameters: data,
      );
      /*get方法
      response = await Dio().get(
        'https://www.easy-mock.com/mock/5c724cf7cb92cf5c294de75a/example/getTest',
        queryParameters: data,
      );
      */
      return response.data;
    } catch (e) {
      return print(e);
    }
  }

  //伪造请求头请求
  void _jikeAction() {
    print('开始向极客时间请求数据......');

    getHttp2().then((val) {
      setState(() {
        showText2 = val['data'].toString();
      });
    });
  }

  Future getHttp2() async {
    try {
      Response response;
      Dio dio = Dio();
      dio.options.headers = httpHeaders; //加上伪造的请求头
      response =
          await dio.get("https://time.geekbang.org/serv/v1/column/newAll");
      print(response);
      return response.data;
    } catch (e) {
      return print(e);
    }
  }
}
